/**
 * A class containing static methods which load images -
 * including images within jar files...
 * <p>
 * @author Tim Tyler
 * @author James Pettit
 * @version 1.12
 * http://mandala.co.uk/imagesinjars/ImageLoader.java
 **/

package com.mintyfresh.tns.client;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class ImageLoader {
	private static ImageLoader image_loader;
	private static Toolkit toolkit;
	/**
	 * ImageLoader, constructor.
	 * <p>
	 * The constructor is private.
	 * There should not be any instances of this
	 * class created outside the private one used
	 * in the class.
	 **/
	private ImageLoader() { 
	} 


	/**
	 * static initialization.
	 * <p>
	 * Create an instance of this class for later use...
	 **/
	static { 
		image_loader = new ImageLoader();
	}


	/**
	 * Get an image.
	 * <p>
	 * Loads a specified image, either from the currect directory,
	 * Or from inside the relevant jar file, whichever is appropriate.
	 **/ 
	public static Image getImage(String name) {
		InputStream in;

		byte[] _array;
		int _array_size;

		toolkit = Toolkit.getDefaultToolkit();

		// debug("Starting to load "+ name + ".");

		try {
			in = image_loader.getClass().getResourceAsStream(name); 

			// Thanks to Karl Schmidt for the following code...
			ByteArrayOutputStream bytes;

			bytes = new ByteArrayOutputStream();
			_array_size = 1024;  // choose a size...
			_array = new byte[_array_size];

			int rb;

			while ((rb = in.read(_array, 0, _array_size)) > -1) {
				bytes.write(_array, 0, rb);
			}

			bytes.close();

			_array = bytes.toByteArray();

			in.close();

			Image image = toolkit.createImage(_array);
			return image;
		}
		catch (IOException e) {
			debug(e.getMessage());
			return null;
		}
	}


	/**
	 * Returns the Toolkit used...
	 * <p>
	 * Allow access to the toolkit used (i.e. access from outside this class)...
	 **/ 
	public static Toolkit getToolkit() {
		return toolkit;
	}


	private static void debug(String o) {
		System.out.println(o);
	}

}
